import { ref } from "vue";
import { takeServiceOrder } from "@/api/service";

// 接单 API
const takeservicegApi = (customerId: number) => {
  const serviceId = uni.getStorageSync("userId");
  return new Promise((resolve, reject) => {
    takeServiceOrder(customerId, serviceId)
      .then(() => {
        resolve({ message: "接单成功！" });
      })
      .catch((error) => {
        // 传递原始错误信息
        reject({
          message: error?.message || "接单时发生错误，请稍后再试！",
          originalError: error,
        });
      });
  });
};

export function usetakeserviceing() {
  const isLoading = ref(false); // 用于显示加载状态
  const errorMessage = ref(""); // 用于显示错误信息

  // 预约服务
  const takeserviceing = async (customerId: number) => {
    if (!customerId) {
      uni.showToast({
        title: "订单ID不能为空",
        icon: "none",
      });
      return false;
    }

    return new Promise((resolve) => {
      // 添加确认弹窗
      uni.showModal({
        title: "确认接单",
        content: "确定要接受这个订单吗？",
        success: async (res) => {
          if (res.confirm) {
            isLoading.value = true; // 开始加载
            try {
              const response: any = await takeservicegApi(customerId); // 调用预约 API
              uni.showToast({
                title: response.message,
                icon: "success",
                duration: 2000,
              });
              resolve(true); // 用户确认并接单成功
            } catch (error: any) {
              errorMessage.value = error.message;
              uni.showToast({
                title: error.message,
                icon: "none",
                duration: 2000,
              });
              resolve(false); // 用户确认但接单失败
            } finally {
              isLoading.value = false; // 结束加载
            }
          } else {
            resolve(false); // 用户取消接单
          }
        },
      });
    });
  };

  return {
    isLoading,
    errorMessage,
    takeserviceing,
  };
}
